package ai.yale.web;

import ai.yale.util.RespMessage;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by asus on 2017/8/18.
 */
@RestController
@CrossOrigin
public class FileController {

    @RequestMapping("/upload")
    public RespMessage upload(MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return RespMessage.fail(400, "文件为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
//        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//        logger.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        String filePath = "E://test//";
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return RespMessage.success("上传成功");
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return RespMessage.fail(400, "上传失败");
    }

    // 多文件上传
    @RequestMapping("/batch")
    public RespMessage handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("files");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        String filePath = "E://test//batch//";
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath + file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return RespMessage.fail(400, "上床失败");
                }
            } else {
                return RespMessage.fail(400, "上床失败");
            }
        }
        return RespMessage.success("上传成功");
    }
}
